#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class XinjiangChangjishiJmsexPolicy(BaseTaxPolicySpider):
    name = 'xinjiang_changjishi_jmsex_policy'
    
    province = '新疆维吾尔自治区'
    city: str = "吉木萨尔县"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格
    custom_settings = {
        "DOWNLOAD_TIMEOUT": 60
    }

    def start_requests(self):
        for source, county, url in [
            ['吉木萨尔县人民政府', "吉木萨尔县", "https://www.jmser.gov.cn/p192/zfb.html"],
            ['吉木萨尔县人民政府', "吉木萨尔县", "https://www.jmser.gov.cn/p192/zbw.html"],
            ['吉木萨尔县人民政府', "吉木萨尔县", "https://www.jmser.gov.cn/p192/xzgfxwj.html"],
            ['吉木萨尔县商务和工业信息化局', "吉木萨尔县", "https://www.jmser.gov.cn/p192/zqskswhgyxxhj.html"],
            ['吉木萨尔县民政局', "吉木萨尔县", "https://www.jmser.gov.cn/p192/ylfwmzj_2.html"],
            ['吉木萨尔县农业农村局', "吉木萨尔县", "https://www.jmser.gov.cn/p192/snbtnyncj.html"],
            ['吉木萨尔县文化体育广播电视和旅游局', "吉木萨尔县", "https://www.jmser.gov.cn/p192/lyfwwlj_2.html"],
        ]:

            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_content, meta={'item': item})

    def parse_content(self, response, **kwargs):
        params = {}
        params['page'] = "1"
        channelids = response.xpath('//script').re_first(r"channelIds\:\s*'?(\d+)")
        if not channelids:
            field = response.url.split('/')[-1].split('.')[0]
            channelids = response.xpath('//script').re_first(r"channelIdsMap\['" + field + r"'\]\s*\?\?\s*'(\d+)'")
        # if not channelids:
        #     print(response.url)
        params['size'] = '15'
        params['channelIds'] = channelids
        print(response.url, channelids)
        yield response.follow("/content/page" + '?' + urllib.parse.urlencode(params), callback=self.parse_list,
                              meta={"params": params})

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        datas = response.json()['data']
        for elem in datas['content']:
            item = Item()
            item['source_url'] = elem['urlWhole']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['releaseTime'].split(" ")[0]
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            pages = datas['totalPages']
            params = response.meta['params']
            print(response.url, f"page: {pages}")
            for page_num in range(2, int(pages) + 1):
                params['page'] = str(page_num)
                yield response.follow("/content/page" + '?' + urllib.parse.urlencode(params), callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl xinjiang_changjishi_jmsex_policy".split())
